<template>
  <div class="ycchuqin">
    <span class="back">
      <router-link to="/main/renshi/kaoqing/kqguanli" style="">返回</router-link>
      <span>
        <span @click="printForm">打印</span>&emsp;
        <router-link to="/main/renshi/kaoqing/ycchuqin-list" style="">列表</router-link>
      </span>
    </span>
    <div class="form">
      <h2>异常情况出勤签卡申请单</h2>
      <div class="operation">
        <button @click="addRecord">新增</button>&emsp;
        <button @click="deleteSelectedRecords">批量删除</button>&emsp;
        <button @click="saveData">保存</button>
      </div>
      <table border="1">
        <thead>
          <tr>
            <th class="checkbox"><input type="checkbox" @change="toggleSelectAll" v-model="selectAll"></th>
            <th>序号</th>
            <th>姓名</th>
            <th>工号</th>
            <th>日期</th>
            <th>班组</th>
            <th>上午</th>
            <th>下午</th>
            <th>加班</th>
            <th>异常情况</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(record, index) in attendanceRecords" :key="index">
            <td class="checkbox"><input type="checkbox" v-model="selectedRecords" :value="index"
                @change="updateSelectAll" /></td>
            <td>{{ index + 1 }}</td>
            <td><input v-model="record.name" /></td>
            <td><input v-model="record.employeeId" /></td>
            <td><input v-model="record.date" type="date" /></td>
            <td><input v-model="record.team" /></td>
            <td><input v-model="record.morning" /></td>
            <td><input v-model="record.afternoon" /></td>
            <td><input v-model="record.overtime" /></td>
            <td><input v-model="record.abnormalSituation" /></td>
            <td><input v-model="record.remark" /></td>
          </tr>
          <tr>
            <td colspan="11">
              <div style="display: grid;grid-template-columns: repeat(3 ,3fr); padding: 0px 0px;">
                <span>制表：<input style="width: 150px;" v-model="formData.tabledBy" /></span>
                <span>审核：<input style="width: 150px;" v-model="formData.reviewedBy" /></span>
                <span>批准：<input style="width: 150px;" v-model="formData.approvedBy" /></span>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <p>※ 各部门需于次日及时将前日的异常出勤状况严格按照以上表单一一填制，并交至企业管理部。</p>
      <p class="foot"><span>表单编号及版本： AM-JY-121 B/0</span> <span>保存期限：长期</span></p>
    </div>
  </div>
</template>
<script>
import { saveAbnormalAttendanceApply, getAbnormalAttendanceApplyDetail } from '@/api/abnormalAttendanceApply';

export default {
  data() {
    return {
      id: null,
      attendanceRecords: [this.getEmptyRecord()],
      formData: {
        tabledBy: '',
        reviewedBy: '',
        approvedBy: ''
      },
      selectedRecords: [],
      selectAll: false
    };
  },
  created() {
    // 从路由参数中获取id
    const id = this.$route.query.id;
    if (id) {
      this.id = id;
      this.fetchDetail(id);
    }
  },
  methods: {
    printForm() {
      window.print();
    },
    getEmptyRecord() {
      return {
        name: '',
        employeeId: '',
        date: '',
        team: '',
        morning: '',
        afternoon: '',
        overtime: '',
        abnormalSituation: '',
        remark: ''
      };
    },
    async fetchDetail(id) {
      try {
        const response = await getAbnormalAttendanceApplyDetail(id);
        const detail = response.data;

        // 设置表单数据
        this.attendanceRecords = [{
          id: detail.id,
          name: detail.name,
          employeeId: detail.employeeId,
          date: detail.date ? detail.date.split('T')[0] : '',
          team: detail.team,
          morning: detail.morning,
          afternoon: detail.afternoon,
          overtime: detail.overtime,
          abnormalSituation: detail.abnormalSituation,
          remark: detail.remark
        }];

        // 设置制表、审核、批准人
        this.formData = {
          tabledBy: detail.tabledBy || '',
          reviewedBy: detail.reviewedBy || '',
          approvedBy: detail.approvedBy || ''
        };
      } catch (error) {
        this.$message.error('获取详情失败：' + error.message);
      }
    },
    // 全选功能
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedRecords = this.attendanceRecords.map((_, index) => index);
      } else {
        this.selectedRecords = [];
      }
    },
    // 更新全选状态
    updateSelectAll() {
      this.selectAll = this.selectedRecords.length === this.attendanceRecords.length;
    },
    // 批量删除功能
    deleteSelectedRecords() {
      if (confirm('确定要删除选中的记录吗？')) {
        this.selectedRecords.sort((a, b) => b - a).forEach(index => {
          this.attendanceRecords.splice(index, 1);
        });
        this.selectedRecords = [];
        this.selectAll = false;
      }
    },
    // 新增记录功能
    addRecord() {
      this.attendanceRecords.push(this.getEmptyRecord());
      this.updateSelectAll();
    },
    // 保存数据功能
    async saveData() {
      try {
        if (this.attendanceRecords.length === 0) {
          this.$message.error('请至少添加一条记录');
          return;
        }

        // 验证必填字段
        for (const record of this.attendanceRecords) {
          if (!record.employeeId) throw new Error('请填写工号');
          if (!record.name) throw new Error('请填写姓名');
          if (!record.date) throw new Error('请选择日期');
        }

        const params = {
          attendanceRecords: this.attendanceRecords.map(record => ({
            ...record,
            // 如果是编辑状态，使用记录自己的id，否则不传id
            id: record.id || null
          })),
          formData: this.formData
        };

        await saveAbnormalAttendanceApply(params);
        this.$message.success('保存成功');
        this.$router.push('/main/renshi/kaoqing/ycchuqin-list');
      } catch (error) {
        this.$message.error('保存失败：' + error.message);
      }
    }
  }
};
</script>
<style scoped lang="scss">
.ycchuqin {
  width: 1200px;
  margin: 0 auto;
  max-width: 1200px;
  height: 100vh;
}

.back {
  display: flex;
  justify-content: space-between;
  padding-top: 10px;
}

p {
  line-height: 30px;
  display: flex;
}

.form {}

.operation {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.foot {
  display: flex;
  justify-content: space-between;
}

table {
  border-collapse: collapse;
  width: 100%;
  text-align: center;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
}

input {
  text-align: center;
  width: 100%;
  border: none;
}

@media print {

  /*@page规则被用来设置打印页面的方向为横向*/
  // @page {
  //   size: landscape;
  // }
  .form {
    max-width: 1070px;
  }

  .container {
    padding: 20px 10px 20px 1px;
    margin-right: 5px;
    box-shadow: 0 0px 0px rgba(255, 255, 255, 0) !important;
  }

  .operation {
    display: none;
  }


  .ycchuqin {
    .back {
      display: none;
    }
  }

  .main-form {
    box-shadow: none;
    padding: 10px;
  }

  table {
    margin: 10px 0px;
  }

  .info-table,
  .content-table,
  .approval-table {
    border: 1px solid #000;

    td,
    th {
      border: 1px solid #000;
    }
  }

  td,
  th {
    padding: 5px;
    border: 1px solid #000;
  }

  .checkbox {
    display: none;
  }

  input {
    border: none !important;
    background-color: transparent !important;
    text-align: center;
  }

  textarea {
    border: 0px !important;
  }
}
</style>